<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <el-header height="60px" class="top-header">
      <div class="header-left">
        <el-icon class="logo-icon"><CameraFilled /></el-icon>
        <span class="logo-text">智能交通监控分析系统</span>
      </div>
      <div class="header-right">
        <el-dropdown>
          <span class="el-dropdown-link">
            <el-avatar :size="small"><User /></el-avatar>
            <span class="username">管理员</span>
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>系统设置</el-dropdown-item>
              <el-dropdown-item>个人中心</el-dropdown-item>
              <el-dropdown-item>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="primary" @click="refreshDashboard" class="refresh-btn">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </el-header>
    
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 系统状态卡片 -->
      <el-row :gutter="20" class="mb-4">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="status-card">
            <template #header>
              <div class="card-header">
                <span>系统状态</span>
                <el-tag :type="systemStatus === 'online' ? 'success' : 'danger'" effect="plain">
                  {{ systemStatus === 'online' ? '在线' : '离线' }}
                </el-tag>
              </div>
            </template>
            <div class="system-status">
              <p><strong>检测引擎:</strong> {{ detectionEngineStatus }}</p>
              <p><strong>模型版本:</strong> {{ modelVersion }}</p>
              <p><strong>活跃摄像头:</strong> {{ activeCameras }} / {{ totalCameras }}</p>
              <p><strong>今日检测数:</strong> {{ todayDetections }}</p>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="status-card">
            <template #header>
              <div class="card-header">
                <span>交通监控指标</span>
              </div>
            </template>
            <div class="traffic-metrics">
              <div class="metric-item">
                <span class="metric-label">头盔佩戴率</span>
                <div class="metric-value" :class="helmetComplianceRate < 80 ? 'low-rate' : 'good-rate'">
                  {{ helmetComplianceRate }}%
                </div>
              </div>
              <div class="metric-item">
                <span class="metric-label">违规事件数</span>
                <div class="metric-value warning-rate">{{ violationCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="status-card">
            <template #header>
              <div class="card-header">
                <span>实时告警</span>
                <el-badge :value="alertCount" class="item" />
              </div>
            </template>
            <div class="recent-alerts">
              <el-scrollbar height="140px">
                <div v-if="recentAlerts.length > 0">
                  <div 
                    v-for="(alert, index) in recentAlerts.slice(0, 5)" 
                    :key="index" 
                    class="alert-item"
                    :class="getAlertClass(alert.type)"
                    @click="viewAlertDetail(alert.id)"
                  >
                    <el-icon :size="16" :color="getAlertColor(alert.type)">
                      <el-icon v-if="alert.type === 'danger'">
                        <WarningFilled />
                      </el-icon>
                      <el-icon v-else-if="alert.type === 'warning'">
                        <Warning />
                      </el-icon>
                      <el-icon v-else>
                        <InfoFilled />
                      </el-icon>
                    </el-icon>
                    <span>{{ alert.message }}</span>
                  </div>
                </div>
                <div v-else class="no-data">暂无告警</div>
              </el-scrollbar>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="status-card">
            <template #header>
              <div class="card-header">
                <span>模型性能</span>
                <el-tag :type="modelPerformance > 0.8 ? 'success' : modelPerformance > 0.6 ? 'warning' : 'danger'" effect="plain">
                  {{ (modelPerformance * 100).toFixed(1) }}% 准确率
                </el-tag>
              </div>
            </template>
            <div class="model-stats">
              <div class="model-metric">
                <span class="metric-label">精准率</span>
                <div class="metric-value">{{ (precision * 100).toFixed(1) }}%</div>
              </div>
              <div class="model-metric">
                <span class="metric-label">召回率</span>
                <div class="metric-value">{{ (recall * 100).toFixed(1) }}%</div>
              </div>
              <div class="model-metric">
                <span class="metric-label">推理速度</span>
                <div class="metric-value">{{ inferenceSpeed }}ms</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 交通监控数据分析 -->
      <el-row :gutter="20" class="mb-4">
        <el-col :xs="24" :md="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>交通流量统计</span>
              </div>
            </template>
            <div class="chart-container">
              <!-- 交通流量图表 -->
              <el-empty description="流量统计图表" />
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :md="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>违规类型分布</span>
              </div>
            </template>
            <div class="chart-container">
              <!-- 违规类型图表 -->
              <el-empty description="违规类型图表" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    
    <!-- 主要功能标签页 -->
    <el-tabs v-model="activeTab" class="main-tabs">
      <!-- 实时监控 -->
      <el-tab-pane label="实时监控" name="realtime-monitor">
        <div class="realtime-monitor-container">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>交通实时监控</span>
                <div class="header-actions">
                  <el-select v-model="selectedCamera" placeholder="选择摄像头" size="small" @change="onCameraChange">
                    <el-option 
                      v-for="camera in availableCameras" 
                      :key="camera.id" 
                      :label="camera.name" 
                      :value="camera.id" 
                    />
                  </el-select>
                  <el-button type="primary" size="small" @click="toggleFullscreen">
                    <el-icon><FullScreen /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>
            
            <!-- 视频监控与检测可视化 -->
            <div class="monitor-content">
              <div class="video-container">
                <VideoStream 
                  title="实时视频监控" 
                  :source="streamSource" 
                  :source-url="streamUrl"
                  :camera-id="selectedCameraId"
                  :show-detection="true"
                  :detection-options="detectionOptions"
                  @detection-update="handleDetectionUpdate"
                />
              </div>
              
              <!-- 实时检测统计面板 -->
              <div class="detection-panel">
                <el-card class="stats-card">
                  <template #header>
                    <span>实时检测统计</span>
                  </template>
                  <div class="real-time-stats">
                    <div class="stat-group">
                      <h4>检测目标</h4>
                      <div v-for="(stat, key) in realTimeStats" :key="key" class="stat-row">
                        <span class="stat-key">{{ getDetectionLabel(key) }}</span>
                        <span class="stat-value" :style="{ color: getDetectionColor(key) }">{{ stat }}</span>
                      </div>
                    </div>
                    <div class="stat-group">
                      <h4>检测状态</h4>
                      <p>检测帧率: {{ detectionFps }} FPS</p>
                      <p>处理延迟: {{ processingLatency }} ms</p>
                      <p>检测准确率: {{ detectionAccuracy }}%</p>
                    </div>
                  </div>
                </el-card>
                
                <el-card class="alerts-card">
                  <template #header>
                    <span>实时告警</span>
                  </template>
                  <div class="real-time-alerts">
                    <el-scrollbar height="200px">
                      <div v-for="alert in recentDetectionAlerts" :key="alert.id" class="alert-entry">
                        <div class="alert-time">{{ formatTime(alert.timestamp) }}</div>
                        <div class="alert-content" :class="`alert-${alert.severity}`">
                          <el-icon :size="14" :color="getAlertSeverityColor(alert.severity)">
                            <el-icon v-if="alert.severity === 'critical'"><WarningFilled /></el-icon>
                            <el-icon v-else-if="alert.severity === 'warning'"><Warning /></el-icon>
                            <el-icon v-else><InfoFilled /></el-icon>
                          </el-icon>
                          <span>{{ alert.message }}</span>
                        </div>
                      </div>
                    </el-scrollbar>
                  </div>
                </el-card>
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
      
      <!-- 文件检测 -->
      <el-tab-pane label="文件检测" name="file-detection">
        <FileUpload 
          :enable-detection-visualization="true"
          :detection-classes="detectionClasses"
          @detection-complete="handleFileDetectionComplete"
        />
      </el-tab-pane>
      
      <!-- 摄像头管理 -->
      <el-tab-pane label="摄像头管理" name="cameras">
        <Cameras 
          :camera-list="camerasList"
          @camera-selected="onCameraSelected"
          @camera-updated="handleCameraUpdate"
        />
      </el-tab-pane>
      
      <!-- 检测记录 -->
      <el-tab-pane label="检测记录" name="detection-records">
        <div class="detection-records-container">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>交通违规检测记录</span>
                <div class="header-actions">
                  <el-date-picker
                    v-model="dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    size="small"
                    @change="fetchDetectionRecords"
                  />
                  <el-select v-model="violationType" placeholder="违规类型" size="small">
                    <el-option label="全部" value="all" />
                    <el-option label="未戴头盔" value="no_helmet" />
                    <el-option label="车辆违规" value="vehicle_violation" />
                    <el-option label="行人违规" value="pedestrian_violation" />
                  </el-select>
                </div>
              </div>
            </template>
            
            <el-table :data="detectionRecordsData" style="width: 100%" @row-click="viewRecordDetail">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="timestamp" label="检测时间" width="180">
                <template #default="scope">
                  {{ formatDateTime(scope.row.timestamp) }}
                </template>
              </el-table-column>
              <el-table-column prop="location" label="监控位置" width="150" />
              <el-table-column prop="camera_name" label="摄像头" width="120" />
              <el-table-column label="违规类型" width="100">
                <template #default="scope">
                  <el-tag 
                    :type="getViolationType(scope.row.violation_type)"
                    size="small"
                  >
                    {{ getViolationLabel(scope.row.violation_type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="违规图片" width="100">
                <template #default="scope">
                  <el-image
                    :src="scope.row.image_url"
                    :preview-src-list="[scope.row.image_url]"
                    style="width: 60px; height: 40px; object-fit: cover;"
                  />
                </template>
              </el-table-column>
              <el-table-column label="处理状态" width="100">
                <template #default="scope">
                  <el-tag 
                    :type="scope.row.status === 'processed' ? 'success' : 'warning'"
                    size="small"
                  >
                    {{ scope.row.status === 'processed' ? '已处理' : '待处理' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="viewRecordDetail(scope.row)">
                    查看详情
                  </el-button>
                  <el-button v-if="scope.row.status !== 'processed'" type="success" size="small" @click="markAsProcessed(scope.row.id)">
                    标记已处理
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <div class="pagination">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalRecords"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </div>
      </el-tab-pane>
      
      <!-- 模型训练与优化 -->
      <el-tab-pane label="模型训练" name="model-training">
        <div class="model-training-container">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>YOLO模型训练与优化</span>
              </div>
            </template>
            
            <div class="model-info">
              <el-descriptions border>
                <el-descriptions-item label="当前模型版本">{{ currentModelVersion }}</el-descriptions-item>
                <el-descriptions-item label="训练状态">{{ trainingStatus }}</el-descriptions-item>
                <el-descriptions-item label="训练数据集">{{ trainingDataset }}</el-descriptions-item>
                <el-descriptions-item label="最后训练时间">{{ formatDateTime(lastTrainingTime) }}</el-descriptions-item>
                <el-descriptions-item label="模型准确率">{{ (modelAccuracy * 100).toFixed(1) }}%</el-descriptions-item>
                <el-descriptions-item label="模型召回率">{{ (modelRecall * 100).toFixed(1) }}%</el-descriptions-item>
              </el-descriptions>
            </div>
            
            <div class="training-section">
              <h4>模型训练配置</h4>
              <el-form :model="trainingForm" :rules="trainingRules" ref="trainingFormRef">
                <el-form-item label="选择预训练模型" prop="pretrained_model">
                  <el-select v-model="trainingForm.pretrained_model" placeholder="选择预训练模型">
                    <el-option label="YOLOv8n (小模型，速度快)" value="yolov8n" />
                    <el-option label="YOLOv8s (中模型，平衡)" value="yolov8s" />
                    <el-option label="YOLOv8m (大模型，精度高)" value="yolov8m" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="训练数据集" prop="dataset">
                  <el-select v-model="trainingForm.dataset" placeholder="选择数据集">
                    <el-option label="交通监控数据集 (本地)" value="local_traffic_dataset" />
                    <el-option label="公开交通数据集" value="public_traffic_dataset" />
                    <el-option label="自定义数据集" value="custom_dataset" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="训练轮数" prop="epochs">
                  <el-input-number v-model="trainingForm.epochs" :min="1" :max="1000" :step="1" />
                </el-form-item>
                
                <el-form-item label="学习率" prop="learning_rate">
                  <el-input-number v-model="trainingForm.learning_rate" :min="0.0001" :max="0.1" :step="0.0001" />
                </el-form-item>
                
                <el-form-item label="重点优化类别" prop="focus_classes">
                  <el-checkbox-group v-model="trainingForm.focus_classes">
                    <el-checkbox label="helmet">头盔检测</el-checkbox>
                    <el-checkbox label="no_helmet">未戴头盔检测</el-checkbox>
                    <el-checkbox label="motorcycle">摩托车检测</el-checkbox>
                    <el-checkbox label="bicycle">自行车检测</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-form>
              
              <div class="training-actions">
                <el-button type="primary" @click="startTraining" :loading="isTraining">开始训练</el-button>
                <el-button type="warning" @click="uploadTrainingData">上传训练数据</el-button>
                <el-button type="info" @click="evaluateModel">评估模型</el-button>
                <el-button type="danger" @click="stopTraining" :disabled="!isTraining">停止训练</el-button>
              </div>
            </div>
            
            <!-- 训练进度和日志 -->
            <div v-if="isTraining" class="training-progress">
              <el-progress :percentage="trainingProgress" :status="trainingProgressStatus" />
              <div class="training-logs">
                <h4>训练日志</h4>
                <el-scrollbar height="200px">
                  <pre class="logs-content">{{ trainingLogs }}</pre>
                </el-scrollbar>
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
      
      <!-- 系统配置 -->
      <el-tab-pane label="系统配置" name="settings">
        <div class="settings-container">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>系统配置</span>
              </div>
            </template>
            
            <el-tabs v-model="settingsTab">
              <!-- 检测配置 -->
              <el-tab-pane label="检测配置" name="detection">
                <el-form :model="detectionSettings" :rules="detectionSettingsRules" ref="detectionSettingsRef">
                  <el-form-item label="检测模式" prop="detection_mode">
                    <el-radio-group v-model="detectionSettings.detection_mode">
                      <el-radio label="realtime">实时检测</el-radio>
                      <el-radio label="offline">离线检测</el-radio>
                      <el-radio label="hybrid">混合模式</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  
                  <el-form-item label="置信度阈值" prop="confidence_threshold">
                    <el-slider 
                      v-model="detectionSettings.confidence_threshold" 
                      :min="0.1" 
                      :max="1.0" 
                      :step="0.05"
                      :marks="{ 0.1: '0.1', 0.3: '0.3', 0.5: '0.5', 0.7: '0.7', 0.9: '0.9' }"
                    />
                    <div class="threshold-value">当前值: {{ detectionSettings.confidence_threshold.toFixed(2) }}</div>
                  </el-form-item>
                  
                  <el-form-item label="检测类别" prop="enabled_classes">
                    <el-checkbox-group v-model="detectionSettings.enabled_classes">
                      <el-checkbox label="person">行人</el-checkbox>
                      <el-checkbox label="car">汽车</el-checkbox>
                      <el-checkbox label="bicycle">自行车</el-checkbox>
                      <el-checkbox label="motorcycle">摩托车</el-checkbox>
                      <el-checkbox label="truck">货车</el-checkbox>
                      <el-checkbox label="helmet">戴头盔</el-checkbox>
                      <el-checkbox label="no_helmet">未戴头盔</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              
              <!-- 告警配置 -->
              <el-tab-pane label="告警配置" name="alerts">
                <el-form :model="alertSettings" :rules="alertSettingsRules" ref="alertSettingsRef">
                  <el-form-item label="告警开关">
                    <el-switch v-model="alertSettings.enable_alerts">启用告警</el-switch>
                  </el-form-item>
                  
                  <el-form-item v-if="alertSettings.enable_alerts" label="告警方式">
                    <el-checkbox-group v-model="alertSettings.alert_channels">
                      <el-checkbox label="system">系统内通知</el-checkbox>
                      <el-checkbox label="email">邮件通知</el-checkbox>
                      <el-checkbox label="sms">短信通知</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  
                  <el-form-item v-if="alertSettings.enable_alerts" label="告警触发条件">
                    <el-checkbox-group v-model="alertSettings.alert_triggers">
                      <el-checkbox label="no_helmet">未戴头盔告警</el-checkbox>
                      <el-checkbox label="overcrowd">人群聚集告警</el-checkbox>
                      <el-checkbox label="vehicle_violation">车辆违规告警</el-checkbox>
                      <el-checkbox label="pedestrian_violation">行人违规告警</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  
                  <el-form-item v-if="alertSettings.enable_alerts" label="告警阈值配置">
                    <el-form-item label="未戴头盔告警阈值" prop="no_helmet_threshold">
                      <el-input-number v-model="alertSettings.no_helmet_threshold" :min="1" :max="100" :step="1" />
                      <span class="threshold-help">连续检测到的未戴头盔人数阈值</span>
                    </el-form-item>
                    
                    <el-form-item label="人群聚集告警阈值" prop="overcrowd_threshold">
                      <el-input-number v-model="alertSettings.overcrowd_threshold" :min="5" :max="100" :step="1" />
                      <span class="threshold-help">单帧检测到的行人数量阈值</span>
                    </el-form-item>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              
              <!-- 系统配置 -->
              <el-tab-pane label="系统" name="system">
                <el-form :model="systemSettings" :rules="systemSettingsRules" ref="systemSettingsRef">
                  <el-form-item label="最大并发流数" prop="max_streams">
                    <el-input-number v-model="systemSettings.max_streams" :min="1" :max="32" :step="1" />
                  </el-form-item>
                  
                  <el-form-item label="检测结果保存时长(天)" prop="data_retention_days">
                    <el-input-number v-model="systemSettings.data_retention_days" :min="1" :max="365" :step="1" />
                  </el-form-item>
                  
                  <el-form-item label="日志级别" prop="log_level">
                    <el-select v-model="systemSettings.log_level" placeholder="选择日志级别">
                      <el-option label="DEBUG" value="debug" />
                      <el-option label="INFO" value="info" />
                      <el-option label="WARNING" value="warning" />
                      <el-option label="ERROR" value="error" />
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
            
            <div class="form-actions">
              <el-button @click="resetAllSettings">重置</el-button>
              <el-button type="primary" @click="saveAllSettings">保存配置</el-button>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 检测详情对话框 -->
    <el-dialog v-model="showDetectionDetailDialog" title="检测详情" width="800px">
      <div v-if="detectionDetail" class="detection-detail">
        <div class="detail-header">
          <h3>{{ detectionDetail.source_name }} - 检测结果</h3>
          <p class="detail-time">{{ formatDateTime(detectionDetail.timestamp) }}</p>
        </div>
        
        <div class="detail-content">
          <div class="detail-image">
            <img :src="detectionDetail.image_url" alt="检测图像" />
          </div>
          
          <div class="detail-stats">
            <h4>检测统计</h4>
            <el-descriptions border>
              <el-descriptions-item label="来源类型">{{ detectionDetail.source }}</el-descriptions-item>
              <el-descriptions-item label="总检测数">{{ detectionDetail.total_detections }}</el-descriptions-item>
              <el-descriptions-item label="置信度均值">{{ (detectionDetail.avg_confidence * 100).toFixed(1) }}%</el-descriptions-item>
              <el-descriptions-item label="处理时间">{{ detectionDetail.processing_time }}ms</el-descriptions-item>
            </el-descriptions>
            
            <h4 class="mt-4">检测目标</h4>
            <div class="detail-results">
              <el-tag 
                v-for="(result, index) in getDetectionResults(detectionDetail.results)" 
                :key="index"
                :type="getResultType(result.type)"
                class="detail-result-tag"
              >
                {{ result.name }}: {{ result.count }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="loading-detail">加载详情中...</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetectionDetailDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import Cameras from '../components/Cameras.vue'
import VideoStream from '../components/VideoStream.vue'
import FileUpload from '../components/FileUpload.vue'

export default {
  name: 'Home',
  components: {
    Cameras,
    VideoStream,
    FileUpload
  },
  setup() {
    // 状态
    const activeTab = ref('video-stream')
    const systemStatus = ref('online')
    const detectionEngineStatus = ref('运行中')
    const activeCameras = ref(3)
    const totalCameras = ref(5)
    const todayDetections = ref(1256)
    const helmetComplianceRate = ref(87.5)
    const alertCount = ref(12)
    const recentAlerts = ref([])
    const stats = reactive({
      person: 42,
      vehicle: 28,
      helmet: 24,
      no_helmet: 7
    })
    
    // 视频流配置
    const streamSource = ref('camera')
    const streamUrl = ref('')
    const selectedCameraId = ref(null)
    
    // 检测历史
    const dateRange = ref([new Date(new Date().setDate(new Date().getDate() - 7)), new Date()])
    const detectionHistoryData = ref([])
    const totalHistory = ref(1000)
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 检测详情
    const showDetectionDetailDialog = ref(false)
    const detectionDetail = ref(null)
    
    // 设置表单
    const settingsForm = reactive({
      detection_mode: 'realtime',
      confidence_threshold: 0.5,
      enabled_classes: ['person', 'car', 'bicycle', 'motorcycle', 'helmet', 'no_helmet'],
      enable_alerts: true,
      alert_triggers: ['no_helmet', 'overcrowd']
    })
    
    const settingsRules = {
      confidence_threshold: [{ required: true, message: '请设置置信度阈值', trigger: 'blur' }],
      enabled_classes: [{ required: true, message: '请至少选择一个检测类别', trigger: 'change' }]
    }
    
    const settingsFormRef = ref(null)
    
    // 初始化数据
    const initializeData = () => {
      fetchSystemStatus()
      fetchRecentAlerts()
      fetchDetectionHistory()
    }
    
    // 获取系统状态
    const fetchSystemStatus = () => {
      // 模拟API调用
      // 实际项目中应该从后端获取真实数据
    }
    
    // 获取最近告警
    const fetchRecentAlerts = () => {
      // 模拟告警数据
      recentAlerts.value = [
        {
          id: 1,
          message: '检测到3名未戴头盔人员',
          type: 'danger',
          timestamp: new Date().toISOString()
        },
        {
          id: 2,
          message: '区域A人群聚集',
          type: 'warning',
          timestamp: new Date(Date.now() - 10 * 60000).toISOString()
        },
        {
          id: 3,
          message: '检测到未戴头盔人员',
          type: 'danger',
          timestamp: new Date(Date.now() - 25 * 60000).toISOString()
        },
        {
          id: 4,
          message: '车辆异常停留',
          type: 'warning',
          timestamp: new Date(Date.now() - 45 * 60000).toISOString()
        }
      ]
    }
    
    // 获取检测历史
    const fetchDetectionHistory = () => {
      // 模拟检测历史数据
      const mockData = []
      for (let i = 1; i <= pageSize.value; i++) {
        const id = (currentPage.value - 1) * pageSize.value + i
        mockData.push({
          id: id,
          timestamp: new Date(Date.now() - i * 60000).toISOString(),
          source: ['camera', 'file', 'video'][Math.floor(Math.random() * 3)],
          source_name: `监控点${Math.floor(Math.random() * 5) + 1}`,
          results: {
            person: Math.floor(Math.random() * 10) + 1,
            car: Math.floor(Math.random() * 5),
            motorcycle: Math.floor(Math.random() * 3),
            helmet: Math.floor(Math.random() * 5),
            no_helmet: Math.floor(Math.random() * 2)
          }
        })
      }
      detectionHistoryData.value = mockData
    }
    
    // 查看检测详情
    const viewDetectionDetail = async (id) => {
      // 模拟获取详情
      detectionDetail.value = {
        id: id,
        timestamp: new Date().toISOString(),
        source: 'camera',
        source_name: '前门监控',
        image_url: 'https://via.placeholder.com/600x400?text=Detection+Result',
        results: {
          person: 3,
          car: 2,
          helmet: 2,
          no_helmet: 1
        },
        total_detections: 8,
        avg_confidence: 0.78,
        processing_time: 45
      }
      showDetectionDetailDialog.value = true
    }
    
    // 刷新仪表盘
    const refreshDashboard = () => {
      initializeData()
      ElMessage.success('数据已刷新')
    }
    
    // 返回上一页
    const handleBack = () => {
      // 处理返回逻辑
      ElMessage.info('返回上一页')
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      fetchDetectionHistory()
    }
    
    const handleCurrentChange = (current) => {
      currentPage.value = current
      fetchDetectionHistory()
    }
    
    // 保存设置
    const saveSettings = () => {
      // 模拟保存
      ElMessage.success('配置已保存')
    }
    
    // 重置设置
    const resetSettings = () => {
      settingsForm.detection_mode = 'realtime'
      settingsForm.confidence_threshold = 0.5
      settingsForm.enabled_classes = ['person', 'car', 'bicycle', 'motorcycle', 'helmet', 'no_helmet']
      settingsForm.enable_alerts = true
      settingsForm.alert_triggers = ['no_helmet', 'overcrowd']
    }
    
    // 获取告警样式类
    const getAlertClass = (type) => {
      return `alert-${type}`
    }
    
    // 获取告警颜色
    const getAlertColor = (type) => {
      const colorMap = {
        danger: '#f56c6c',
        warning: '#e6a23c',
        info: '#606266'
      }
      return colorMap[type] || '#606266'
    }
    
    // 获取检测结果列表
    const getDetectionResults = (results) => {
      const resultList = []
      const nameMap = {
        person: '行人',
        car: '汽车',
        bicycle: '自行车',
        motorcycle: '摩托车',
        truck: '货车',
        helmet: '戴头盔',
        no_helmet: '未戴头盔'
      }
      
      for (const [key, value] of Object.entries(results)) {
        if (value > 0 && nameMap[key]) {
          resultList.push({
            type: key,
            name: nameMap[key],
            count: value
          })
        }
      }
      
      return resultList
    }
    
    // 获取结果标签类型
    const getResultType = (type) => {
      const typeMap = {
        person: 'primary',
        car: 'success',
        bicycle: 'info',
        motorcycle: 'warning',
        truck: 'info',
        helmet: 'success',
        no_helmet: 'danger'
      }
      return typeMap[type] || 'info'
    }
    
    // 格式化日期时间
    const formatDateTime = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
    
    // 组件挂载时初始化
    onMounted(() => {
      initializeData()
    })
    
    return {
      activeTab,
      systemStatus,
      detectionEngineStatus,
      activeCameras,
      totalCameras,
      todayDetections,
      helmetComplianceRate,
      alertCount,
      recentAlerts,
      stats,
      streamSource,
      streamUrl,
      selectedCameraId,
      dateRange,
      detectionHistoryData,
      totalHistory,
      currentPage,
      pageSize,
      showDetectionDetailDialog,
      detectionDetail,
      settingsForm,
      settingsRules,
      settingsFormRef,
      refreshDashboard,
      handleBack,
      fetchDetectionHistory,
      viewDetectionDetail,
      handleSizeChange,
      handleCurrentChange,
      saveSettings,
      resetSettings,
      getAlertClass,
      getAlertColor,
      getDetectionResults,
      getResultType,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.home-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.system-status p,
.recent-alerts p {
  margin: 8px 0;
}

.alert-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 5px 0;
}

.alert-danger {
  color: #f56c6c;
}

.alert-warning {
  color: #e6a23c;
}

.alert-info {
  color: #606266;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #909399;
  font-style: italic;
}

.detection-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.main-tabs {
  margin-top: 20px;
}

.detection-history-container,
.settings-container {
  padding: 0;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.threshold-value {
  text-align: center;
  margin-top: 5px;
  font-size: 14px;
  color: #606266;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.detection-detail {
  padding: 10px;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-header h3 {
  margin: 0;
}

.detail-time {
  color: #909399;
  font-size: 14px;
  margin-top: 5px;
}

.detail-content {
  display: flex;
  gap: 20px;
}

.detail-image {
  flex: 1;
  max-width: 50%;
}

.detail-image img {
  max-width: 100%;
  border-radius: 4px;
}

.detail-stats {
  flex: 1;
}

.detail-stats h4 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
}

.detail-results {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.detail-result-tag {
  margin-bottom: 10px;
}

.mt-4 {
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.loading-detail {
  text-align: center;
  padding: 40px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-content {
    flex-direction: column;
  }
  
  .detail-image {
    max-width: 100%;
  }
}
</style>